<?php

/**
 * @author liyi
 * @copyright 2018.12.06
 * 掘金小美女
 */
namespace Mininggame\Controller;
use Common\Controller\ApiController;
use Think\Model;
use Think\Log;

class IndexController extends ApiController {

    const GAME_TYPE = 'Mininggame';  // 游戏类型

    const CACHE_KEY = 'mining';  // 游戏全局缓存键

    const DB_USER_NAME = 'mining_game.users'; // 游戏用户数据表

    const DB_INVITELOG_NAME = 'mining_game.invite_log'; // 游戏邀请数据表

    const INVITE = "mining:invite:sid:%"; // 邀请次数

    const MINING_KEY = "mining:%s:sid:%s"; // 渠道来源缓存键

    const MINING_COUNT_KEY = "mining:count"; // 渠道来源统计缓存键

    const MINING_RANK_LIST = "mining:rankList"; // 排行榜列表

    const MINING_DBID = 3; // 缓存数据编号

    public function __construct()
    {
        parent::__construct();

        $uid = $this->isLogin(self::GAME_TYPE);
        $id = I('id','','int');

        if(empty($uid)) {
            $uid = $id;
            //$uid = $this->isParamLogin($id);
        }
        if (!$uid) {
            $this->response(1,'请先登录');
        }
        $source = I('source',0,'int');  // 渠道来源
        $this->sid = $source;   // 渠道
        $this->uid = $uid;      // 用户登录id
    }

    // 排行榜
    public function rankingList()
    {
        $uid = $this->uid;
        $gold = I('gold','','string');
        $where['id'] = $uid;

        $redis = REDIS('activity');
        $redis->select(2);
        $hash_key = self::MINING_RANK_LIST;

        $ret = $this->getRankList($hash_key,true,2,'gold');

        if(empty($ret)) {   // 缓存为空时
            $where['nickname'] = array('neq','');
            $where['avatar'] = array('neq','');
            $map['black_list'] = 1;
            $map['gold'] = array('neq',0);
            $ret = M('users')->field('id,nickname,avatar,gold,score')->where($map)->order('score desc')->limit(200)->select();
            foreach($ret as $k=>$v) {
                if(!empty($v['nickname']) && !empty($v['avatar'])){
                    $id = $v['id'];
                    $flag = $redis->hSet($hash_key,$id, json_encode($v));
                    //$redis->exprieAt($hash_key,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期
                    //$redis->expire($hash_key,300);// 缓存5分钟过期
                }
            }

        }

        // 客户数据更新(与最后一名比较)
        $lastList = end($ret);
        $lastGold = intval($lastList['gold']);
        if($gold > $lastGold) {
            $where['status'] = 2;
            $where['black_list'] = 1;
            $where['gold'] = array('neq',0);
            $userInfo = M('users')->field('id,nickname,avatar,gold,score')->where($where)->find();
            $data = array('id'=>$userInfo['id'],'gold'=>$gold,'nickname'=>$userInfo['nickname'],'avatar'=>$userInfo['avatar'],'score'=>$userInfo['score']);
            $this->setRankList($hash_key,2,$data,$userInfo['id'],'gold',$gold);
            M('users')->where($where)->save(array('gold'=>$gold));  //点击排行版更新用户数据

            $ret = $this->getRankList($hash_key,true,2,'gold');
        }

        $this->response(0, "OK",array('randList'=>$ret));
    }

    // 跟新虚拟货币
    public function setGolds() {

        $uid = $this->uid;
        $gold = I('gold','0','string');
        $diamonds = I('diamonds','0','string');

        if(!empty($gold)) {
            $data['gold'] = $gold;
        }
        if(!empty($diamonds)) {
            $data['diamonds'] = $diamonds;
        }

        $map['id'] = $uid;
        $ret = M('users')->where($map)->save($data);

        $this->response(0,"操作成功");
    }

    // 邀请记录 插入
    public function inviteRecord()
    {
        $uid = $this->uid;
        $sid = $this->sid;
        $invite_uid = I('invite_uid',0,'int'); //邀请人用户
        $type = I('type',1,'int'); // 邀请类型 1:每日邀请 2：招募保安 3：招募会计 4：招募经理 5：招募总监
        $time = date('Y-m-d');
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表
        $cacheKey = self::CACHE_KEY; // 缓存键
        $cacheval =  sprintf(self::INVITE,$sid) ; // 缓存值

        $dbId = self::MINING_DBID;
        if( $uid != $invite_uid ) {  //如果不是自己邀请自己
            // 转发邀请记录
            $typeForward = array("101", "102", "103");
            if (in_array($type, $typeForward)) {
                $type_table = 'mining';   // redis表
                $this->getForward($uid, $invite_uid, $type_table, $type);
            }
            $incr = $this->commInviteRecord($uid,$invite_uid,$type,$time,$dbname,$cacheKey,$cacheval,$dbId);
            $this->getChannelCount(self::MINING_COUNT_KEY,$sid,'invite',$incr,$dbId);
        }else{
            $this->response(3, "自己不能邀请自己");
        }

    }

    // 招人列表 当天邀请
    public function hiringList() {
        //$uid = $this->uid;
        $uid = isset($this->uid)?$this->uid:I('post.id');
        // 邀请类型 1:每日邀请 2：招募保安  3：招募会计 4：招募经理 5：招募总监  6:金币加速
        $post = I('post.type');  // type[2,3,4,5,6] json数组
        if(!empty($post)){
            if(is_array($post)){
                $type = $post;
            }else{
                $type = json_decode($post,true);
            }
        }else{
            $type=1;
        }

        $sort = I('post.sort'); //
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表 mining_game.invite_log
        $dbname2 = self::DB_USER_NAME;  //  游戏用户数据表 mining_game.users

        if($type !=99){
            if($sort ==1){
                $time = date('Y-m-d');// 今日邀请
            }else{
                $time = '';// 所有邀请
            }
        }

        $list = $this->commUserInvite($uid,$type,$dbname,$dbname2,$time);// 邀请记录
        $info =$temp =array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $info[$v['type']][] = $v;//所有标识
                unset($temp);
            }
        }

        //$info = array('2'=>$guard,'3'=>$finance,'4'=>$manager,'5'=>$director,'6'=>$speed,'number'=>$list['number']);
        $num = $list['number'];
        $this->response(0, "ok",$info,$num);

    }

    // 邀请好友列表 关联
    public function hiringLists() {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $array_id = array('uid'=>'uid','i_id'=>'invite_uid');// 对比Id
        $id = 'id';// 根据Id
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表 mining_game.invite_log
        $dbname2 = self::DB_USER_NAME;  //  游戏用户数据表 mining_game.users

        $list = $this->commUserInvites($id,$array_id,$uid,$dbname,$dbname2);// 邀请记录

        $info =array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $v['update_time'] = strtotime($v['update_time']);
                $info[] = $v;//所有标识
            }
        }

        $this->response(0, "ok",$info);

    }

    // 每日任务列表
    public function everyDayTask() {

        $uid = $this->uid;
        $time = date('Y-m-d');

        $dbname = self::DB_INVITELOG_NAME;
        $dbname2 = self::DB_USER_NAME;

        $list = $this->commUserInvite($uid,$type=1,$dbname,$dbname2,$time);

        $this->response(0, "ok",$list);
    }

    // 记录用户点击分享按钮的次数
    public function setShare() {
        $id = I('id','','string'); // 用户userid
        $type = I('type',1,'int');  // 1:分享次数 2：分享完成(暂停) 3：看完视频次数 4：点击视频次数
        $sid = $this->sid;  // 渠道来源

        if(!in_array($type,array(1,3,4))) {
            $this->response(1,'非法的分享类型');
        }
        $arr = array(1=>'share',3=>'video_close',4=>'video_click');
        $typeName = $arr[$type];

        $userKey = self::CACHE_KEY;
        $userVal = sprintf(self::MINING_KEY,$typeName,$sid);  //用户主键分享到群
        $countKey = self::MINING_COUNT_KEY;

        $incr = $this->countLog($userKey,$userVal);  // 记录看完视频的次数

        $this->getChannelCount($countKey,$sid,$typeName,$incr);

        $this->response(0,'ok');
    }


    // 记录游戏成绩
    public function upgrade()
    {
        $uid = $this->uid;  // 用户ID
        $gold = I('gold','0','string');
        $diamonds = I('diamonds','0','string');
        $score = I('score',0,'int');
        $warehouse = $_POST['warehouse'];

        if(!empty($gold)) {
            $data['gold'] = $gold;
        }
        if(!empty($diamonds)) {
            $data['diamonds'] = $diamonds;
        }
        if(!empty($score)) {
            $data['score'] = $score;
        }
        if(!empty($warehouse)) {
            $data['warehouse'] = json_encode($warehouse);
        }
        $map['id'] = $uid;
        $ret = M('users')->where($map)->save($data);

        $this->response(0, "ok");
    }


    // 每日大礼包（存储）
    public function setGiftData(){

        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID
        $json = I('post.data'); // Json

        if(empty($uid) || empty($json)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $goods=htmlspecialchars_decode($json);
            $goods_list=html_entity_decode($goods);
            $data['data'] = $goods_list;//转义后
            $data['create_time'] = time();
            $data['time'] = date('Y-m-d H:i:s');
            $user = M('git')->where(array('uid'=>$uid))->find();

            if($user){
                $res = M('git')->where(array('uid'=>$uid))->save($data);
            }else{
                $res = M('git')->add($data);
            }
            //echo M('git')->getLastSql();
            if($res){
                $this->response(0, "ok");
            }else{
                $this->response(2, "大礼包存储失败");
            }

        }
    }


    // 每日大礼包（获取）
    public function getGiftData(){
        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID
        if(empty($uid)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $info = M('git')->field('uid,data')->where($data)->find();
            if(!empty($info)){
                $info['data'] = json_decode($info['data'],true);
            }
            $this->response(0, "ok",$info);
        }
    }


    // 记录在线时间
    public function setTime(){
        $uid = I('id','','int');
        $line_time = I('time',0,'int');

        if(empty($uid) || empty($line_time)){
            $this->response(1,"参数不能为空");
        }
        $user = M('users')->where(array('id'=>$uid))->find();
        if(empty($user)){
            $this->response(2,"用户不存在");
        }
        $res = M('users')->where(array('id'=>$uid))->setInc('line_time',$line_time);
        $data['line_time'] = M('users')->where(array('id'=>$uid))->getField('line_time');
        if ($res){
            $this->response(0, "ok",$data);
        }
    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }

    // 转发记录接口 转发次数人数记录
    public function forward(){
        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID
        $type = I('type','','int'); // 1:查询;2:添加;3:删除
        $type_table = 'mining';   // redis表
        $invite_uid = I('invite_uid','','int');
        $this->getForward($uid,$invite_uid,$type_table,$type);
    }

}